package com.aqie.advanced.template;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Function:
 * @Author: aqie
 * @Date: 2019/9/6 8:43
 */
@Slf4j
public class ThymeleafBootstrap {
    public static void main(String[] args) throws IOException {
        // 1.构建引擎
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        // 2,创建渲染上下文
        Context context = new Context();
        context.setVariable("name", "aqie");

        // 读取模板内容 classpath:/template/index.html  ResourceLoader
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:/templates/index.html");
        File templateFile = resource.getFile();
        // 文件流
        FileInputStream inputStream = new FileInputStream(templateFile);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 输入 复制到输出
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();


        // 3. 模板内容
        String content = outputStream.toString("UTF-8");

        String result = templateEngine.process(content, context);
        log.info(result);
    }
}
